<?php

namespace App\Models\WorkOrder;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Relations\HasMany;

class WorkOrderRejectModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'work_order_rejects';

    protected $fillable = [
        'workOrderNo',
        'step',
        'status',
        'createdByUid',
        'updatedByUid',
        'createdAt',
        'updatedAt',
        'isDeleted',
    ];

    const STATUS_INIT = 0;
    const STATUS_OK   = 1;

    public function detailsRel(): HasMany
    {
        return $this->hasMany(WorkOrderRejectDetailModel::class, 'rejectId', 'id');
    }

    /**
     * 更新status
     * @param string $workOrderNo
     * @param int $status
     * @param int $step
     * @return int
     */
    public static function saveStatus(string $workOrderNo, int $status, int $step = 0): int
    {
        return self::query()
            ->where('workOrderNo', $workOrderNo)
            ->when(
                $step, function ($query) use ($step) {
                $query->where('step', $step);
            }
            )
            ->where('status', self::STATUS_INIT)
            ->update(['status' => $status]);
    }

    /**
     * 驳回转交
     * @param int $oriUid
     * @param int $targetUid
     * @return int
     */
    public static function transfer(int $oriUid, int $targetUid): int
    {
        return self::query()->where('createdByUid', $oriUid)->where('status', self::STATUS_INIT)->update(['createdByUid' => $targetUid]);
    }
}
